<?php
namespace app\{{$module}}\controller;

use app\base\controller\BaseCtrl;
use think\Db;

class Base extends BaseCtrl
{
    protected $beforeActionList = ['check_auth'];
    protected function check_login()
    {
        $admin_login = cookie('admin_login');
        $admin_id    = session('admin_id');
        if (is_null($admin_id) && is_null($admin_login)) {
            return false;
        }
        if (!is_null($admin_login)) {
            $admin_login = explode('@@@', simple_decrypt($admin_login));
            if (is_null($admin_id)) {
                $admin_id = $admin_login[0];
                session('admin_id', $admin_id);
            }
        }
        $admin = Db::table('admin_admin')->field(true)->where('id', $admin_id)->where('disabled', 0)->find();
        if (is_null($admin) || (!is_null($admin_login) && $admin['password'] !== $admin_login[1])) {
            session('admin_id', null);
            cookie('admin_login', null);
            return false;
        }
        return $admin;
    }
    protected function check_auth()
    {
        $admin = $this->check_login();
        if ($admin !== false) {
            if ($admin['role']) {
                $role = Db::table('admin_role')->field(true)->where('id', $admin['role'])->where('disabled', 0)->find();
                if (is_null($role)) {
                    session('admin_id', null);
                    cookie('admin_login', null);
                    $admin = false;
                } else {
                    if ($role['auth']) {
                        $menu = Db::table('admin_menu')->field(true)->where('route', $this->route)->where('disabled', 0)->find();
                        if (!is_null($menu) && strpos($role['auth'], $menu['id']) !== false) {
                            session('admin_id', null);
                            cookie('admin_login', null);
                            $admin = false;
                        }
                    }
                }
            }
        }
        if ($admin === false) {
            if ($this->post || (isset($this->get['page']) && isset($this->get['limit']))) {
                $this->returnAPI('登录信息有误,请重新登录', -10000);
            } else {
                $this->redirect('/admin/login/login');
            }
        }
    }
}
